<?php
/**
 * 快递100
 * Date: 2019/6/19
 * Author: Mr.Z
 */

namespace App\Services;


use App\Exceptions\ApiException;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\ConnectException;
use GuzzleHttp\Psr7\Request;
use Illuminate\Support\Facades\Log;

class ExpressService
{
    public $key;
    public $customer;

    public function __construct()
    {
        $this->key = env('EXPRESS_KEY');
        $this->customer = env('EXPRESS_CUSTOMER');
    }

    /**
     * EMS ems
     * 顺丰 shunfeng
     * 申通 shentong
     * 圆通 yuantong
     * 中通 zhongtong
     * 韵达 yunda
     * 京东物流 jd
     * @return mixed
     */
    public function orderquery($com, $num)
    {
        $url = 'http://poll.kuaidi100.com/poll/query.do';    //实时查询请求地址
        //参数设置
        $key = $this->key;             //客户授权key
        $customer = $this->customer;   //查询公司编号
        $param = array(
            'com'      => $com,        //快递公司编码
            'num'      => $num,        //快递单号
            'phone'    => '',          //手机号
            'from'     => '',          //出发地城市
            'to'       => '',          //目的地城市
            'resultv2' => '1',          //开启行政区域解析
        );
        $post_data = $this->sign($key, $customer, $param);

        //$result = $this->curlPost($url, $post_data);

        $result = $this->getResponse($url,$post_data);

        return $result;
    }

    /**
     * 签名
     * @param $key
     * @param $customer
     * @param $param
     * @return array
     */
    public static function sign($key, $customer, $param)
    {
        //请求参数
        $post_data = array();
        $post_data["customer"] = $customer;
        $post_data["param"] = json_encode($param);
        $sign = md5($post_data["param"] . $key . $post_data["customer"]);
        $post_data["sign"] = strtoupper($sign);
        $params = "";
        foreach ($post_data as $k => $v) {
            $params .= "$k=" . urlencode($v) . "&";
        }
        $post_data = substr($params, 0, -1);
        w_log('物流查询签名' . "\n" . json_encode($post_data), 'express');

        return $post_data;
    }

    /**
     * post请求
     * @param $url
     * @param $post_data
     * @return mixed
     * @throws ApiException
     */
    protected function curlPost($url, $post_data)
    {
        //发送post请求
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($ch);
        $data = str_replace("\"", '"', $result);
        $data = json_decode($data);

        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_errno($ch);
            curl_close($ch);
            throw new ApiException('curl出错，错误码:' . $error, 20000);
        }
    }

    /**
     * 函数功能 通过GuzzleHttp请求三方接口
     * @name getResponse
     * @param void
     * @author Mr.Liu
     * @return JsonStr
     * @datetime 2019/6/21 13:48
     */
    protected function getResponse($url,$post_data){

        try{
            $client = new \GuzzleHttp\Client();
            $response = $client->request('POST',$url, [
                'query'      => $post_data,
                'timeout'    => 3
            ]);

            if($response->getStatusCode() != 200)
                throw new \Exception('接口数据异常');

            return \GuzzleHttp\json_decode($response->getBody()->getContents(),true);

        }catch (ConnectException $connectException){
            Log::channel('express_api')->info('接口异常',['exception' => $connectException]);
        }catch (\Exception $exception){
            Log::channel('express_api')->error('程序异常',['exception' => $exception]);
        }
    }
}